import store from "@/store";
import { Message } from "element-ui";
import { blobToDataURL } from "../utils";
import { fixWebmDuration } from "./fixWebmDuration";

// 开始录屏
export const startRecordScreen = async () => {
  var startTimestamp;
  if (!navigator.mediaDevices) {
    if (window.location.protocol !== "https:") {
      Message.error({
        customClass: 'el-message-index',
        message:"使用HTTPS协议的页面才支持该功能"});
      return;
    }
    Message.error({
      customClass: 'el-message-index',
      message:"当前页面不支持屏幕录制"});
    return;
  }
  navigator.mediaDevices
    .getDisplayMedia({ video: { mediaSource: "screen" }, audio: true })
    .then(stream => {
      let chunks = [];
      const recorder = new MediaRecorder(stream);
      recorder.start(1000);
      recorder.onstart = function (e) {
        startTimestamp = Date.now();
      };
      recorder.ondataavailable = event => {
        chunks.push(event.data);
      };
      recorder.onstop = function () {
        console.log("屏幕录制结束");
        console.log("chunks", chunks);
        let completeBlob = new Blob(chunks, {
          type: "video/mp4"
        });
        var duration = Date.now() - startTimestamp;
        fixWebmDuration(completeBlob, duration, function (fixedBlob) {
          blobToDataURL(fixedBlob, function (result) {
            console.log(result);
            store.commit("orange/openDialog", {
              key: "SaveFolderDlg",
              value: {
                video: result
              }
            });
          });
        });
        // var url = window.URL.createObjectURL(blob);
        // console.log("videoStream", url);
      };
    })
    .catch(error => {
      console.log(error);
    });
};
